
package com.itheima.controller.backend.security;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class SpringSecurityUserService implements UserDetailsService {
    //查找服务，实现查询数据库
    @Autowired
    private UserService userService;

    //根据用户名查询数据库中用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 使用userService的方法查询用户信息
        User user = userService.findByUsername(username);
        log.info("用户信息为{}", user);
        // 查询用户角色和权限信息
        HashSet<GrantedAuthority> set = new HashSet<>();
        List<String> roleKeys = userService.getRoleKeysById(user.getId());
        roleKeys.forEach(roleKey -> set.add(new SimpleGrantedAuthority(roleKey)));
//        set.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        // 返回带用户名，密码，权限列表的user对象User(username,user.getPassword(),list)
        return new org.springframework.security.core.userdetails.User(
                username,
                user.getPassword(),
                set
        );
    }
}